<?php
/**
 * @author Anh Nguyen
 * @copyright 2012
 */
 defined('APP') or die('Denied access !');
 
 class Core
 {
    public static $config = array();
    public static $module = array();
    
    public static function init($config)
    {
        self::$config = $config;
        self::getModules();
        spl_autoload_register(array('Core','autoload'));
        Router::init();
    }
    
    public static function autoload($classname)
    {
        $classname = strtolower($classname);
        $class = explode('_', $classname);
        if( isset($class[1])) {
            $class[1] = $class[1] . 's';
        }
        $class = implode('/', $class) . '.php';
        foreach(array(CORE_PATH, MODULE_PATH) as $path)
        {
            if( file_exists($path . DS . $class)) {
                require_once $path . DS . $class;
                return true;
            }
        }
        header('Location: ' . Core::site_url());
    }
    
    private static function getModules()
    {
        $handle = opendir(MODULE_PATH);
        while( ($entry = readdir($handle)) !== FALSE)
        {
            if( strpos($entry, '.') === FALSE) {
                self::$module[] = $entry;
            }
        }
    }
    
    public static function site_url($uri = '')
    {
        $url = BASE_URL . $uri;
        if($uri != '') {
            $url = $url . self::$config['url_prefix'];
        }
        return $url;
    }
    
    public static function redirect($url)
    {
        header("Location: " . $url);
    }
    
    public static function ValidCaptcha($sUserCode, $bCaseInsensitive = true) 
    {
        if ($bCaseInsensitive) {
            $sUserCode = strtoupper($sUserCode);
        }
        
        if ($sUserCode == $_SESSION[self::$config['session_pre'] . 'captcha']) {
            // clear to prevent re-use
            unset($_SESSION[self::$config['session_pre'] . 'captcha']);
            return true;
        }
        return false;
    }
    
    public static function config_item($item)
    {
        return self::$config[$item];
    }
    
    public static function encrypt_pass ( $pass )
    {
        return sha1(md5(sha1($pass)));
    }
 }
?>